#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理模块
负责系统配置的读取和保存
"""

import json
import os
import logging
from pathlib import Path
from typing import Any, Dict, Optional

logger = logging.getLogger(__name__)

class Config:
    """配置管理类"""
    
    def __init__(self, config_file: str = None):
        if config_file is None:
            # 默认使用项目根目录下的data目录
            project_root = Path(__file__).parent.parent.parent
            data_dir = project_root / "data"
            data_dir.mkdir(exist_ok=True)
            config_file = str(data_dir / "config.json")
        
        self.config_file = config_file
        self.config = self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                logger.error(f"加载配置文件失败: {e}")
                return self.get_default_config()
        else:
            # 如果配置文件不存在，创建默认配置
            default_config = self.get_default_config()
            self.save_config(default_config)
            return default_config
    
    def save_config(self, config: Dict[str, Any] = None):
        """保存配置文件"""
        if config is None:
            config = self.config
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            logger.info(f"配置文件已保存: {self.config_file}")
        except Exception as e:
            logger.error(f"保存配置文件失败: {e}")
    
    def get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "database": {
                "path": "sample_management.db",
                "backup_interval": 24,
                "backup_path": "backups/"
            },
            "communication": {
                "tcp": {
                    "default_host": "192.168.137.232",
                    "default_port": 5000,
                    "timeout": 30,
                    "heartbeat_interval": 30
                },
                "serial": {
                    "default_port": "COM1",
                    "default_baudrate": 9600,
                    "data_bits": 8,
                    "stop_bits": 1,
                    "parity": "N"
                }
            },
            "ui": {
                "window_size": [1400, 900],
                "window_position": [100, 100],
                "theme": "default",
                "language": "zh_CN"
            },
            "export": {
                "default_format": "excel",
                "excel_template": "templates/excel_template.xlsx",
                "pdf_template": "templates/pdf_template.pdf"
            },
            "hospital": {
                "name": "",
                "address": "",
                "contact": "",
                "logo_path": ""
            },
            "print": {
                "page_size": "A4",
                "margin_top": 20.0,
                "margin_bottom": 20.0,
                "margin_left": 20.0,
                "margin_right": 20.0,
                "font_size": 12,
                "font_family": "SimSun"
            },
            "warning_ranges": {
                "HbA1c": {"min": 4.0, "max": 6.0, "unit": "%"},
                "Glucose": {"min": 3.9, "max": 6.1, "unit": "mmol/L"},
                "Cholesterol": {"min": 3.1, "max": 5.7, "unit": "mmol/L"}
            },
            "logging": {
                "level": "INFO",
                "file": "sample_management.log",
                "max_size": 10,
                "backup_count": 5
            },
            "backup": {
                "auto_backup": True,
                "auto_backup_interval": 24,
                "close_backup": True,
                "encryption_type": "AES",
                "max_backup_files": 30,
                "backup_database": True,
                "backup_config": True,
                "backup_logs": True,
                "backup_path": "backups/",
                "compression_level": 6,
                "include_temp_files": False
            }
        }
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        keys = key.split('.')
        value = self.config
        
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key: str, value: Any):
        """设置配置值"""
        keys = key.split('.')
        config = self.config
        
        # 遍历到最后一个键
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        # 设置值
        config[keys[-1]] = value
        
        # 保存配置
        self.save_config()
    
    def get_database_path(self) -> str:
        """获取数据库路径"""
        return self.get("database.path", "sample_management.db")
    
    def get_tcp_config(self) -> Dict[str, Any]:
        """获取TCP配置"""
        return self.get("communication.tcp", {})
    
    def get_serial_config(self) -> Dict[str, Any]:
        """获取串口配置"""
        return self.get("communication.serial", {})
    
    def get_ui_config(self) -> Dict[str, Any]:
        """获取UI配置"""
        return self.get("ui", {})
    
    def get_hospital_info(self) -> Dict[str, Any]:
        """获取医院信息"""
        return self.get("hospital", {})
    

    
    def get_warning_ranges(self) -> Dict[str, Any]:
        """获取警告区间配置"""
        return self.get("warning_ranges", {})
    
    def get_backup_config(self) -> Dict[str, Any]:
        """获取备份配置"""
        return self.get("backup", {})
    
    def get_backup_path(self) -> str:
        """获取备份路径"""
        return self.get("backup.backup_path", "backups/")
    
    def is_auto_backup_enabled(self) -> bool:
        """是否启用自动备份"""
        return self.get("backup.auto_backup", True)
    
    def get_backup_interval(self) -> int:
        """获取备份间隔（小时）"""
        return self.get("backup.auto_backup_interval", 24)
    
    def is_close_backup_enabled(self) -> bool:
        """是否启用程序关闭备份"""
        return self.get("backup.close_backup", True)
    
    def get_encryption_type(self) -> str:
        """获取加密类型"""
        return self.get("backup.encryption_type", "AES")
    
    def get_max_backup_files(self) -> int:
        """获取最大备份文件数"""
        return self.get("backup.max_backup_files", 30) 